<?php

namespace App\Services;

use App\Models\Goods;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Query\Builder;

class GoodsService extends BaseService {
    public function countGoodsOnSale(): int
    {
        return Goods::query()->where('is_on_sale','=',1)
            ->count('id');
    }

    public function listGoods($params,$columns): LengthAwarePaginator
    {
        $query = $this->getQueryByParams($params);
        if (isset($params['categoryId'])) {
            $query = $query->where('category_id','=',$params['categoryId']);
        }
        return $query->orderBy($params['sort'],$params['order'])->paginate($params['limit'], $columns, $pageName = 'page', $params['page']);
    }

    public function listL2Category($params): array
    {
        $query = $this->getQueryByParams($params);
        return $query->select(['category_id'])->pluck('category_id')->unique()->toArray();
    }

    private function getQueryByParams($params) {
        $query = Goods::query()->where('is_on_sale','=',1);
        if (isset($params['brandId'])) {
            $query = $query->where('brand_id','=',$params['brandId']);
        }
        if (isset($params['isNew'])) {
            $query = $query->where('is_new','=',$params['isNew']);
        }
        if (isset($params['isHot'])) {
            $query = $query->where('is_hot','=',$params['isHot']);
        }
        if (isset($params['keyword'])) {
            $keywords = $params['keyword'];
            $query = $query->where(function (Builder $query) use ($keywords){
                $query->where('keywords','like',"%$keywords%")
                    ->orWhere('name','like',"%$keywords%");
            });
        }
        return $query;
    }
}
